<?php
/**
 * Handler File Class
 *
 * @author admin <admin@wolive.cc>
 * @email admin@wolive.cc
 * @date 2017/06/01
 */

namespace app\admin\controller;

use app\admin\model\Admins;
use app\extra\push\Pusher;
use think\Paginator;
use app\admin\iplocation\Ip;
use EasyWeChat\Foundation\Application;

date_default_timezone_set("Asia/shanghai");

/**
 *
 * 设置控制器.
 */
class Set extends Base
{
    /**
     * 对话pusher类.
     *
     * @return void
     */
    public function chats()
    {

        $login = $_SESSION['Msg'];
        $arr = $this->request->post();

        $raw_content = $arr['content'];

        $arr['content'] = Base::chatDecode($arr['content']);

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $arr['business_id'] = $login['business_id'];
        $arr['service_id'] = $login['service_id'];

        $arr['direction'] = 'to_visiter';
        $arr["timestamp"] = time();
        $channel = bin2hex($arr['visiter_id'] . '/' . $arr['business_id']);

        // 查找商家信息，判断是否被禁用
        $state = Admins::table('wolive_business')->where('business_id', $arr['business_id'])->value('state');
        if ($state != 'open') {
            return ['code' => 500, 'msg' => '该账号已经被禁用'];
        }

        try {

            $arr['avatar'] = $login['avatar'];

            $pusher->trigger("cu" . $channel, 'my-event', array('message' => $arr));

            unset($arr['avatar']);

            Admins::table('wolive_chats')->insert($arr);

            $e = '';
            $visiter = Admins::table('wolive_visiter')->where(['visiter_id' => $arr['visiter_id'], 'business_id' => $arr['business_id']])->find();
            if ($visiter['from_url'] == '微信') {
                try {
                    $weixin_config = Admins::table('wolive_weixin_config')->where('business_id', $arr['business_id'])->find();
                    if ($weixin_config) {
                        $options = [
                            'app_id' => $weixin_config['appid'],
                            'secret' => $weixin_config['secret'],
                            'token' => $weixin_config['token'],
                            'aes_key' => $weixin_config['aes_key'],
                        ];

                        $app = new Application($options);

                        $content = $raw_content;

                        // 表情替换
                        $content = preg_replace_callback('/face\[(.*?)\]/', function ($matches) {
                            return "[{$matches[1]}]";
                        }, $content);

                        // 图片消息
                        if (preg_match('/^\!\[.*?\]\((.*?)\)$/', $content, $match)
                            && is_file($file = __DIR__ . '/../../../public' . $match[1])) {
                            $material = $app->material_temporary;
                            $upload = $material->upload('image', $file);
                            $image = new \EasyWeChat\Message\Image();
                            $image->media($upload->media_id);
                            $app->staff->message($image)->to($arr['visiter_id'])->send();
                        // 语音消息
                        } elseif (preg_match('/voice\((.*?)\)/', $content, $match)
                            && is_file($file = __DIR__ . '/../../../public' . parse_url($match[1], PHP_URL_PATH))) {
                            $material = $app->material_temporary;
                            $upload = $material->upload('voice', $file);
                            $voice = new \EasyWeChat\Message\Voice();
                            $voice->media($upload->media_id);
                            $app->staff->message($voice)->to($arr['visiter_id'])->send();
                        // 文件消息
                        } elseif(preg_match('/file\[(.*?)\]\((.*?)\)/', $content, $match)) {
                            $scheme = !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://';
                            $host = $scheme . $_SERVER['SERVER_NAME'];
                            $app->staff->message("[文件{$match[1]}]\r\n$host{$match[2]}")->to($arr['visiter_id'])->send();
                        // 文本消息
                        } else {
                            $app->staff->message($content)->to($arr['visiter_id'])->send();
                        }
                    }
                } catch (\Exception $e) {} catch(\Error $e){}
            }

            $data = ['code' => 0, 'msg' => 'success', 'data' => $e ? $e->getMessage()."\n".$e->getTraceAsString():''];
            return $data;

        } catch (\Exception $e) {

            $error = $e->getMessage();
            $data = ['code' => 3, 'msg' => $error];
            return $data;
        }

    }

    /**
     * 删除访客类.
     *
     * @return mixed
     */
    public function deletes()
    {

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );


        $login = $_SESSION['Msg'];
        $post = $this->request->post();
        Admins::table('wolive_queue')->where([
            'visiter_id'  => $post['visiter_id'],
            'business_id' => $login['business_id']
        ])->update(['state' => 'complete']);

        $pusher->trigger("ud" . $login['service_id'], 'on_chat', array('message' => ''));

        $data = ['code' => 0, 'msg' => 'success'];

        return $data;

    }


    /**
     * 转接客服类.
     * @return [type] [description]
     */
    public function getswitch()
    {
        $login = $_SESSION['Msg'];
        $post = $this->request->post();

        $admin = Admins::table('wolive_service')->where('service_id', $post['id'])->find();

        $visiter_id = ($post['visiter_id']);
        $service_id = ($post['id']);
        $group_id  = $admin['groupid'];
        $business_id = $login['business_id'];

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $channel = bin2hex($post['visiter_id'] . '/' . $business_id);


        $pusher->trigger("cu" . $channel, 'getswitch', array('message' => $admin));

        $pusher->trigger('kefu' . $service_id, 'getswitch', array('message' => $post['name'] . "  转接访客给你"));

        Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'service_id'  => $login['service_id'],
            'business_id' => $business_id,
        ])->update([
            'state'       => 'complete'
        ]);

        // 更新队列
        $rows = Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'service_id'  => $service_id,
            'business_id' => $business_id,
        ])->find();
        if ($rows) {
            Admins::table("wolive_queue")->where([
                'visiter_id'  => $visiter_id,
                'service_id'  => $service_id,
                'business_id' => $business_id,
            ])->update([
                'visiter_id'  => $visiter_id,
                'service_id'  => $service_id,
                'business_id' => $business_id,
                'groupid'     => $group_id,
                'state'       => 'normal'
            ]);
        } else {
            Admins::table("wolive_queue")->insert([
                'visiter_id'  => $visiter_id,
                'service_id'  => $service_id,
                'business_id' => $business_id,
                'groupid'     => $group_id,
                'state'       => 'normal'
            ]);
        }

        $arr = ['code' => 0, 'msg' => '转接成功！'];
        return $arr;
    }


    /**
     * 认领访客类.
     *
     * @return mixed
     */
    public function get()
    {
        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $login = $_SESSION['Msg'];
        $post = $this->request->post();
        $visiter_id = ($post['visiter_id']);

        $where = [
            'visiter_id'  => $visiter_id,
            'business_id' => $login['business_id'],
            'service_id'  => 0,
            'state'       => 'normal'
        ];
        // group为0的客服可以认领任意分组id的访客
        if ($login['groupid'] != 0) {
            $where['groupid'] = $login['groupid'];
        }
        // 更新队列表对应记录为当前客服认领
        $result = Admins::table('wolive_queue')->where($where)->update(['service_id' => $login['service_id']]);
        if (!$result) {
            $arr = ['msg' => '该客服已经被认领', 'groupid' => $login['groupid']];
            $pusher->trigger("all" . $login['business_id'], 'on_notice', array('message' => $arr));
            return;
        }

        $channel = bin2hex($visiter_id. '/' . $login['business_id']);

        // 更新service_id为0的历史消息为和当前客服的消息
        Admins::table('wolive_chats')->where(['visiter_id' => $visiter_id, 'business_id' => $login['business_id']])->update(['service_id' => $login['service_id']]);

        // 获取默认的常用语
        $words = Admins::table('wolive_sentence')->where('service_id', $login['service_id'])->where('state', 'using')->find();
        if ($words['content'] == "") {
            $words['content'] = "你好!";
        }
        $chats = array(
            'avatar' => $login['avatar'],
            'content' => $words['content']
        );

        $arr = ['msg' => '访客被认领', 'groupid' => $login['groupid']];
        $pusher->trigger("all" . $login['business_id'], 'on_notice', array('message' => $arr));
        $pusher->trigger("cu" . $channel, 'first_word', array('message' => $chats));
        $pusher->trigger("cu" . $channel, 'cu_notice', array('message' => $login));

        $data = ['code' => 0, 'msg' => 'success'];
        return $data;
    }

    /**
     * 排队列表类.
     *
     * @return mixed
     */
    public function getwait()
    {
        $login = $_SESSION['Msg'];

        if ($login['groupid'] == 0) {
            $visiters = Admins::table('wolive_queue')->where('service_id', 0)->where('business_id', $login['business_id'])->where('state', 'normal')->select();
        } else {
            $visiters = Admins::table('wolive_queue')->where('service_id', 0)->where('business_id', $login['business_id'])->where('state', 'normal')->where('groupid', $login['groupid'])->select();
        }


        $waiters = [];

        foreach ($visiters as $v) {
            $data = Admins::table('wolive_visiter')->where('visiter_id', $v['visiter_id'])->where('business_id', $login['business_id'])->find();

            $class = Admins::table('wolive_group')->where('id', $v['groupid'])->find();

            if ($data) {
                $waiters[] = $data;
            }

            if ($class) {
                $data['groupname'] = $class['groupname'];
            } else {
                $data['groupname'] = '普通咨询';
            }

            if (!empty($data['timestamp'])) {
                $data['timestamp'] = $this->formatTime(strtotime($data['timestamp']));
            }
        }
        $count = count($waiters);

        $data = ['code' => 0, 'data' => $waiters, 'num' => $count];
        return $data;
    }

    /**
     * 对话列表类.
     *
     * @return mixed
     */
    public function getchats()
    {

        $login = $_SESSION['Msg'];

        $visiters = Admins::table('wolive_queue')->where(['service_id' => $login['service_id'], 'business_id' => $login['business_id']])->where('state', 'normal')->column('visiter_id');

        function extract_attrib($tag)
        {
            preg_match_all('/(id|alt|title|src)=("[^"]*")/i', $tag, $matches);
            $ret = array();
            foreach ($matches[1] as $i => $v) {
                $ret[$v] = $matches[2][$i];
            }
            return $ret;
        }

        $visiter_info = Admins::table('wolive_visiter')->where('visiter_id', 'in' ,$visiters)->where('business_id', $login['business_id'])->column('*', 'visiter_id');

        $chatonlinearr = [];
        $chatofflinearr = [];
        foreach ($visiter_info as $visiter_id => $data) {

            $chats2 = Admins::table('wolive_chats')->where(['visiter_id' => $visiter_id, 'service_id' => $login['service_id']])->order('cid desc')->find();

            $result = Admins::table('wolive_chats')->where('visiter_id', $visiter_id)->where('business_id', $login['business_id'])->where('state', 'unread')->where('direction', 'to_service')->count();

            $newcontent = preg_replace('/<div><a .*? download.*?>.*?<\/a><\/div>/', '[文件]', $chats2['content']);
            $newcontent = preg_replace('/<div.*?<audio src=.*?><\/audio>.*?<\/div>/i','[语音]', $newcontent);
            $newcontent = preg_replace('/<img src=.*?emoji\/emo_.*?>/i','[表情]', $newcontent);
            $newcontent = preg_replace('/<img .*?src=.*?>/i','[图片]', $newcontent);
            $newcontent = preg_replace('/^<a[^<>]+>.+?<\/a>$/','[超链接]', $newcontent);

            $data['content'] = strip_tags($newcontent);
            $data['count'] = $result;
            $data['timestamp'] = $this->formatTime($chats2['timestamp']);
            $data['timestamp2'] = $chats2['timestamp'];

            if ($data['state'] == 'online') {
                $chatonlinearr[] = $data;
            } else {
                $chatofflinearr[] = $data;
            }

        }

        reset($chatonlinearr);
        reset($chatofflinearr);
        $chatofflinearr = array_reverse($chatofflinearr);
        $chatarr = array_merge($chatonlinearr, $chatofflinearr);


        if ($chatarr) {
            $sort1 = $sort2 = [];
            foreach ($chatarr as $key => $item) {
                $sort1[] = isset($item['timestamp2']) ? $item['timestamp2'] : 0;
                $sort2[] = intval($item['state'] == 'online');
            }
            array_multisort($sort2, SORT_DESC, $sort1, SORT_DESC, $chatarr);
            // 如果记录数大于50个，则尝试关闭多余的离线的会话
            $del_arr = array_slice($chatarr, 50);
            $visiter_id_del = [];
            foreach ($del_arr as $item) {
                if ($item['state'] == 'offline') {
                    $visiter_id_del[$item['visiter_id']] = $item['visiter_id'];
                }
            }
            if ($visiter_id_del) {
                Admins::table('wolive_queue')->where(['service_id' => $login['service_id'], 'business_id' => $login['business_id']])->where('state', 'normal')->where('visiter_id', 'in', $visiter_id_del)->update(['state'=>'complete']);
                foreach ($chatarr as $key => $item) {
                    if (isset($visiter_id_del[$item['visiter_id']])) {
                        unset($chatarr[$key]);
                    }
                }
            }

            $data = ['code' => 0, 'data' => $chatarr];
            return $data;

        } else {
            $data = ['code' => 1, 'msg' => '暂时没有数据！'];
            return $data;
        }
    }


    /**
     * 获取当前聊天信息类.
     *
     * @return string
     */
    public function chatdata()
    {
        $login = $_SESSION['Msg'];
        $service_id = $login['service_id'];
        $post = $this->request->post();

        if ($post["hid"] == '') {

            $data = Admins::table('wolive_chats')->where(['service_id' => $service_id, 'visiter_id' => $post['visiter_id'], 'business_id' => $login['business_id']])->order('timestamp desc')->limit(10)->select();

            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->find();

            $sdata = Admins::table('wolive_service')->where('service_id', $service_id)->find();

            foreach ($data as $v) {

                if ($v['direction'] == 'to_service') {
                    $v['avatar'] = $vdata['avatar'];
                } else {

                    $v['avatar'] = $sdata['avatar'];
                }

            }

            reset($data);

        } else {


            $data = Admins::table('wolive_chats')->where(['service_id' => $service_id, 'visiter_id' => $post['visiter_id'], 'business_id' => $login['business_id']])->where('cid', '<', $post['hid'])->order('timestamp desc')->limit(10)->select();

            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->find();

            $sdata = Admins::table('wolive_service')->where('service_id', $service_id)->find();


            foreach ($data as $v) {

                if ($v['direction'] == 'to_service') {
                    $v['avatar'] = $vdata['avatar'];
                } else {
                    $v['avatar'] = $sdata['avatar'];
                }

            }

            reset($data);

        }

        $result = array_reverse($data);

        $data = ['code' => 0, 'data' => $result];
        return $data;
    }

    /**
     * 获取所有该用户的聊天记录。
     * [history description]
     * @return [type] [description]
     */
    public function history()
    {
        $post = $this->request->post();

        $login = $_SESSION['Msg'];

        if ($post["hid"] == '') {
            $data = Admins::table('wolive_chats')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->order('timestamp desc')->limit(10)->select();
            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->find();

            foreach ($data as $v) {

                if ($v['direction'] == 'to_service') {
                    $v['avatar'] = $vdata['avatar'];
                    $v['name'] = $vdata['visiter_name'];
                } else {
                    $sdata = Admins::table('wolive_service')->where('service_id', $v['service_id'])->find();
                    $v['avatar'] = $sdata['avatar'];
                    $v['name'] = $sdata['nick_name'];
                }
            }
            reset($data);
        } else {

            $data = Admins::table('wolive_chats')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->where('cid', '<', $post['hid'])->order('timestamp desc')->limit(10)->select();
            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->find();

            foreach ($data as $v) {

                if ($v['direction'] == 'to_service') {
                    $v['avatar'] = $vdata['avatar'];
                    $v['name'] = $vdata['visiter_name'];
                } else {
                    $sdata = Admins::table('wolive_service')->where('service_id', $v['service_id'])->find();
                    $v['avatar'] = $sdata['avatar'];
                    $v['name'] = $sdata['nick_name'];
                }
            }
            reset($data);
        }

        $result = array_reverse($data);
        $data = ['code' => 0, 'data' => $result];
        return $data;
    }


    /**
     * 获取ip地址类.
     *
     * @return string
     */
    public function getipinfo()
    {

        $post = $this->request->get();
        $ip = $post['ip'];
        if (long2ip(ip2long($ip)) !== $ip) {
            return ['code' => 0, 'data' => explode(' ', $ip)];
        }
        $data = Ip::find($ip);
        $arr = ['code' => 0, 'data' => $data];
        return $arr;
    }

    /**
     * 标记已看信息.
     *
     * @return mixed
     */
    public function getwatch()
    {
        $login = $_SESSION['Msg'];
        $business_id = $login['business_id'];
        $post = $this->request->post();
        $time_start = microtime(true);
        $result = Admins::table('wolive_chats')->where('visiter_id', $post['visiter_id'])->where('business_id', $business_id)->update(['state' => 1]);
        $diff = microtime(true) - $time_start;
        $arr = ['code' => 0, 'msg' => 'success', 'data' => $diff];
        return $arr;
    }

    /**
     * 获取未看信息条数类.
     *
     * @return mixed
     */
    public function getmessage()
    {
        $login = $_SESSION['Msg'];
        $business_id = $login['business_id'];
        $post = $this->request->post();

        $channel = $post['channel'];

        $str = pack('H*', $channel);

        $arr = explode("/", $str);

        $visiter_id = $arr[0];

        $result = Admins::table('wolive_chats')->where('visiter_id', $visiter_id)->where('business_id', $business_id)->where('state', 'unread')->count();
        $data = ['code' => 0, 'data' => $result];
        return $data;
    }

    /**
     * 拖到黑名单.
     *
     * @return mixed
     */
    public function blacklist()
    {
        $post = $this->request->post();
        $login = $_SESSION['Msg'];

        $result = Admins::table('wolive_queue')->where('visiter_id', $post['visiter_id'])->where('business_id', $login['business_id'])->update(['state' => 'in_black_list']);

        $arr = ['code' => 0, 'msg' => 'success', 'data' => $result];
        return $arr;

    }

    /**
     * 获取该business_id下所用的黑名单信息.
     *
     * @return bool|string
     */
    public function getblackdata()
    {
        $login = $_SESSION['Msg'];

        $visiters = Admins::table('wolive_queue')->where('state', 'in_black_list')->where('business_id', $login['business_id'])->column('visiter_id','visiter_id');
        $visiters = $visiters ? array_unique($visiters) : [];
        $blackers = [];
        foreach ($visiters as $v) {
            $data = Admins::table('wolive_visiter')->where('visiter_id', $v)->where('business_id', $login['business_id'])->find();
            $blackers [] = $data;
        }

        $data = ['code' => 0, 'data' => $blackers];

        return $data;
    }


    /**
     * 设置常用语默认值.
     *
     * @return mixed
     */
    public function settalkdefa()
    {
        $post = $this->request->post();
        $login = $_SESSION['Msg'];
        $result = Admins::table('wolive_sentence')->where([
            'sid' => $post['tid'],
            'service_id' => $login['service_id']
        ])->update(['state' => 'using']);
        Admins::table("wolive_sentence")->where('sid', '<>', $post['tid'])->where('service_id', $login['service_id'])
            ->update(['state' => 'unuse']);

        $arr = ['code' => 0, 'msg' => 'success', 'data' => $result];
        return $arr;
    }

    /**
     * 常用语删除.
     *
     * @return bool
     */
    public function tdelete()
    {
        $post = $this->request->post();
        $result = Admins::table('wolive_sentence')->where('sid', $post['tid'])->delete();


        $arr = ['code' => 0, 'msg' => 'success', 'data' => $result];

        return $arr;
    }

    /**
     * 查看历史记录类.
     *
     * @return mixed
     */
    public function getviews()
    {

        $login = $_SESSION['Msg'];
        $post = $this->request->post();
        $vid = $post["visiter_id"];
        $service_id = $post['service_id'];

        $business_id = $login['business_id'];
        $time = $post['puttime'];
        if ($time == 1) {
            $puttime = strtotime("-1 month");
            $result = Admins::table('wolive_chats')->where(['visiter_id' => $vid, 'business_id' => $business_id])->where('timestamp', '>', $puttime)->order('timestamp')->select();

            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $vid)->where('business_id', $login['business_id'])->find();
            $sdata = Admins::table('wolive_service')->where('service_id', $service_id)->find();

            foreach ($result as $v) {

                if ($v['direction'] == 'to_service') {

                    $v['avatar'] = $vdata['avatar'];
                } else {

                    $v['avatar'] = $sdata['avatar'];
                }

            }

            reset($result);


        } else if ($time == 7) {
            $puttime = strtotime("-1 week");
            $result = Admins::table('wolive_chats')->where(['visiter_id' => $vid, 'business_id' => $business_id])->where('timestamp', '>', $puttime)->order('timestamp')->select();

            $data = Admins::table('wolive_visiter')->where('visiter_id', $vid)->where('business_id', $login['business_id'])->find();

            foreach ($result as $v) {
                if ($v['direction'] == 'to_service') {
                    $v['avatar'] = $data['avatar'];
                } else {

                    $data = Admins::table('wolive_service')->where('service_id', $v['service_id'])->find();
                    $v['avatar'] = $data['avatar'];
                }
            }

            reset($result);


        }

        $data = ['code' => 0, 'data' => $result];
        return $data;
    }

    /**
     * 自定义查看历史对话记录类.
     *
     * @return mixed
     */
    public function getdesignForViews()
    {
        $login = $_SESSION['Msg'];
        $post = $this->request->post();

        $s_time = strtotime($post['start']);
        $e_time = strtotime($post['end']) + 24 * 60 * 60;

        $vid = $post["channel"];
        $business_id = $login['business_id'];

        $result = Admins::table('wolive_chats')->where(['visiter_id' => $vid, 'business_id' => $business_id])->where('timestamp', '>=', $s_time)->where('timestamp', '<=', $e_time)->select();

        foreach ($result as $v) {
            if ($v['direction'] == 'to_service') {
                $data = Admins::table('wolive_visiter')->where('visiter_id', $v['visiter_id'])->where('business_id', $login['business_id'])->find();
                $v['avatar'] = $data['avatar'];
            } else {

                $data = Admins::table('wolive_service')->where('service_id', $v['service_id'])->find();
                $v['avatar'] = $data['avatar'];
            }
        }

        reset($result);


        $data = ['code' => 0, 'data' => $result];
        return $data;
    }

    /**
     * 获取该客服交谈过的所有客服.
     *
     * @return mixed
     */
    public function getvisiters()
    {
        $login = $_SESSION['Msg'];
        $post = $this->request->post();
        $id = $post["service"];

        $visiters = Admins::table('wolive_chats')->distinct(true)->field('visiter_id')->where(['service_id' => $id, 'business_id' => $login['business_id']])->select();

        $visiterdata = [];
        foreach ($visiters as $v) {
            $visiterdata[] = $v['visiter_id'];
        }

        if ($visiterdata) {
            $data = Admins::table('wolive_visiter')->where('business_id', $login['business_id'])->where('visiter_id', 'in', $visiterdata)->select();
        } else {
            $data = '';
        }

        $data = ['code' => 0, 'data' => $data];
        return $data;
    }

    /**
     * 获取排队人数.
     *
     * @return mixed
     */
    public function getwaitnum()
    {
        $login = $_SESSION['Msg'];

        if ($login['groupid'] == 0) {
            $result = Admins::table('wolive_queue')->where(['service_id' => 0, 'business_id' => $login['business_id']])->where('state', 'normal')->count();

        } else {
            $result = Admins::table('wolive_queue')->where(['service_id' => 0, 'business_id' => $login['business_id'], 'groupid' => $login['groupid']])->where('state', 'normal')->count();

        }


        $data = ['code' => 0, 'data' => $result];
        return $data;
    }

    /**
     * 获取访客的状态
     *
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getstatus()
    {
        $post = $this->request->post();
        $res = Admins::table('wolive_visiter')->where('channel', $post['channel'])->find();
        $data = ['code' => 0, 'data' => $res];
        return $data;
    }

    /**
     * 获取当前对话信息
     *
     */
    public function getchatnow()
    {
        $post = $this->request->post();
        $login = $_SESSION['Msg'];
        $visiter_id = $post['sdata']['visiter_id'];
        $res = Admins::table('wolive_queue')->where('visiter_id', $visiter_id)->where('business_id', $login['business_id'])->where('service_id', $login['service_id'])->find();

        // var_dump($res['state']);exit;

        $sdata = Admins::table('wolive_visiter')->where('visiter_id', $visiter_id)->where('business_id', $login['business_id'])->find();

        $chats = Admins::table('wolive_chats')->where(['visiter_id' => $visiter_id, 'service_id' => $login['service_id'], 'direction' => 'to_service'])->order('cid desc')->find();

        if ($res['state'] == 'complete') {

            $res = Admins::table('wolive_queue')->where('visiter_id', $visiter_id)->where('business_id', $login['business_id'])->update(['state' => 'normal']);
        }

        $data = ['code' => 0, 'msg' => 'success'];
        return $data;
    }


    public function apply()
    {
        $login = $_SESSION['Msg'];
        $post = $this->request->post();

        $visiter = Admins::table('wolive_visiter')->where('visiter_id', $post['id'])->where('business_id', $login['business_id'])->find();

        if (!$visiter) {

            $data = ['code' => 1, 'msg' => '该访客数据已被清理！'];

            return $data;
        }

        $type = $visiter['state'];

        if ($type == -1) {

            $data = ['code' => 1, 'msg' => '对方不在线'];
            return $data;
        }

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );

        $host = ahost;
        $port = aport;
        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $pusher->trigger("cu" . $visiter['channel'], "video", array("message" => "申请视频连接", "channel" => $post['channel'], "avatar" => $post['avatar'], 'username' => $post['name']));
        $data = ['code' => 0, 'msg' => 'success'];

        return $data;

    }

    /**
     * 拒绝视屏类方法
     *
     */
    public function refuse()
    {
        $post = $this->request->post();

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $pusher->trigger("cu" . $post['channel'], "video-refuse", array("message" => "对方拒绝视频连接！"));
    }


    /**
     * 更改 video
     * @return array
     */
    public function videoswitch()
    {
        $login = $_SESSION['Msg'];
        if($login['level'] == 'service'){
            return [
                'code' => 1,
                'data' => '没有权限',
            ];
        }
        $post = $this->request->post();
        $type = $post['type'];
        if ($type == 'open') {
            $res = Admins::table('wolive_business')->where('business_id', $login['business_id'])->update(['video_state' => 'open']);

        } else {
            $res = Admins::table('wolive_business')->where('business_id', $login['business_id'])->update(['video_state' => 'close']);

        }

        if ($res) {
            $arr = [
                "code" => 0,
                "data" => "修改成功"
            ];
            return $arr;
        } else {
            $arr = [
                "code" => 0,
                "data" => "修改失败"
            ];
            return $arr;
        }
    }

    /**
     * 更改 audio
     * @return array
     */
    public function audioswitch()
    {
        $login = $_SESSION['Msg'];
        if($login['level'] == 'service'){
            return [
                'code' => 1,
                'data' => '没有权限',
            ];
        }
        $post = $this->request->post();
        $type = $post['type'];
        if ($type == 'open') {
            $res = Admins::table('wolive_business')->where('business_id', $login['business_id'])->update(['audio_state' => 'open']);

        } else {
            $res = Admins::table('wolive_business')->where('business_id', $login['business_id'])->update(['audio_state' => 'close']);

        }

        if ($res) {
            $arr = [
                "code" => 0,
                "data" => "修改成功"
            ];
            return $arr;
        } else {
            $arr = [
                "code" => 0,
                "data" => "修改失败"
            ];
            return $arr;
        }
    }

    /**
     * 更改 voice
     * [voiceswitch description]
     * @return [type] [description]
     */
    public function voiceswitch()
    {
        $login = $_SESSION['Msg'];
        if($login['level'] == 'service'){
            return [
                'code' => 1,
                'data' => '没有权限',
            ];
        }
        $post = $this->request->post();
        $type = $post['type'];
        $res = Admins::table('wolive_business')->where('business_id', $login['business_id'])->update(['voice_state' => $type]);

        if ($res) {
            $arr = [
                "code" => 0,
                "data" => "修改成功"
            ];
            return $arr;
        } else {
            $arr = [
                "code" => 0,
                "data" => "修改失败"
            ];
            return $arr;
        }
    }

    /**
     * 更改 分配模式
     * [getswitchmodel description]
     * @return [type] [description]
     */
    public function getswitchmodel()
    {
        $login = $_SESSION['Msg'];
        if($login['level'] == 'service'){
            return [
                'code' => 1,
                'data' => '没有权限',
            ];
        }
        $post = $this->request->post();
        $type = $post['type'];
        $res = Admins::table('wolive_business')->where('business_id', $login['business_id'])->update(['distribution_rule' => $type]);
        if ($res) {
            $arr = [
                "code" => 0,
                "data" => "修改成功"
            ];
            return $arr;
        } else {
            $arr = [
                "code" => 0,
                "data" => "修改失败"
            ];
            return $arr;
        }

    }

    /**
     * 添加或修改tab面版内容
     * [gettab description]
     * @return [type] [description]
     */
    public function gettab()
    {

        $post = $this->request->post();
        $post['business_id'] = $_SESSION['Msg']['business_id'];
        $post['content'] = $_POST['content'];

        if (isset($post['tid'])) {

            $res = Admins::table('wolive_tablist')->where('tid', $post['tid'])->update(['title' => $post['title'], 'content' => $post['content'], 'content_read' => $post['content_read']]);

        } else {

            $res = Admins::table('wolive_tablist')->insert($post);
        }

        $arr = ['code' => 0, 'msg' => '成功'];
        return $arr;
    }

    /**
     * 删除tab面版
     * [getdeleteTab description]
     * @return [type] [description]
     */
    public function getdeleteTab()
    {

        $post = $this->request->post();
        $id = $post['tid'];
        $result = Admins::table('wolive_tablist')->where('tid', $id)->delete();

        if ($result) {
            $arr = ['code' => 0, 'msg' => '删除成功'];
            return $arr;
        }
    }

    /**
     *
     * [getshowTab description]
     * @return [type] [description]
     */
    public function getshowTab()
    {
        $post = $this->request->post();
        $id = $post['tid'];
        $res = Admins::table('wolive_tablist')->where('tid', $id)->find();

        if ($res) {
            $arr = ['code' => 0, 'msg' => 'success', 'data' => $res];
            return $arr;
        }

    }

    /**
     * 删除常见问题
     * [getdeleteQuestion description]
     * @return [type] [description]
     */
    public function getdeleteQuestion()
    {
        $post = $this->request->post();
        $id = $post['qid'];

        $result = Admins::table("wolive_question")->where('qid', $id)->delete();

        if ($result) {
            $arr = ['code' => 0, 'msg' => '删除成功'];
            return $arr;
        }
    }

    /**
     *
     * [uploadVoice description]
     * @return [type] [description]
     */
    public function uploadVoice()
    {

        $http_type = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $file = $this->request->file('file');

        if ($file) {
            $newpath = ROOT_PATH . "/public/assets/upload/voices/";
            $info = $file->move($newpath, time().rand() . ".wav");

            if ($info) {
                $file_data = file_get_contents($info->getRealPath());
                if (false !== strpos($file_data, '<?php')) {
                    unlink($info->getRealPath());
                    return json_encode([
                        'code' => 400,
                        'msg'  => '文件非法',
                    ]);
                }
                $imgname = $info->getFilename();

                $imgpath = $http_type . $_SERVER['HTTP_HOST'] . "/assets/upload/voices/" . $imgname;
                $arr = [
                    'data' => [
                        'src' => $imgpath
                    ]
                ];
                return json_encode($arr);
            } else {
                return false;
            }
        }

    }


    /**
     * 图片上传.
     *
     * @return [type] [description]
     */
    public function upload()
    {
        try {
            $file = $this->request->file("upload");
            $name = $_FILES["upload"]["name"];

            $arr = explode(".", $name);
            $ext = $arr[1];

            if ($ext == 'html' || $ext == 'htm' || $ext == 'jsp' || $ext == 'php' || $ext == 'js') {

                $error = "不支持该文件格式！";


                $data = [
                    "code" => -1,
                    "msg" => $error,
                    "data" => ""
                ];

                return $data;
            }

            if ($file) {
                $newpath = ROOT_PATH . "/public/upload/images/";
                $info = $file->move($newpath, time().rand());
                if ($info) {

                    $file_data = file_get_contents($info->getRealPath());
                    if (false !== strpos($file_data, '<?php')) {
                        unlink($info->getRealPath());
                        return ([
                            'code' => 400,
                            'msg'  => '文件非法',
                        ]);
                    }

                    $imgname = $info->getFilename();

                    $imgpath = "/upload/images/" . $imgname;

                    // 生成缩略图,减少图片尺寸
                    $realpath = $info->getRealPath();
                    $image = \think\Image::open($realpath);
                    $image->thumb(1024, 1024)->save($realpath);

                    $data = [
                        "code" => 0,
                        "msg" => "",
                        "data" => $imgpath
                    ];

                    return $data;
                }
            }
        } catch (\Exception $e) {
            $error = "有异常";

            $data = [
                "code" => -1,
                "msg" => $error,
                "data" => ""
            ];

            return $data;
        }

    }

    /**
     * 文件上传.
     *
     * @return [type] [description]
     */
    public function uploadfile()
    {
        $file = $this->request->file("folder");

        $name = $_FILES["folder"]["name"];

        $ext = substr($name, strripos($name, ".") + 1);

        if ($ext == 'html' || $ext == 'htm' || $ext == 'jsp' || $ext == 'php' || $ext == 'js') {

            $error = "不支持该文件格式！";


            $data = [
                "code" => -1,
                "msg" => $error,
                "data" => ""
            ];

            return $data;
        }


        if ($file) {
            $newpaths = ROOT_PATH . "/public/upload/files/";
            $info = $file->move($newpaths, time().rand());
            if ($info) {

                $file_data = file_get_contents($info->getRealPath());
                if (false !== strpos($file_data, '<?php')) {
                    unlink($info->getRealPath());
                    return ([
                        'code' => 400,
                        'msg'  => '文件非法',
                    ]);
                }

                $imgname = $info->getFilename();

                $imgpath = "/upload/files/" . $imgname;

                $data = [
                    "code" => 0,
                    "msg" => "",
                    "data" => $imgpath
                ];

                return $data;
            }
        }
    }

    /**
     *
     * [createFrontjs description]
     * @return [type] [description]
     */
    public function createFrontjs()
    {


        $http_type = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

        $login = $_SESSION['Msg'];

        $business_id = $login['business_id'];
        $url = $http_type . $_SERVER['HTTP_HOST'];
        $js = @file_get_contents($url . "/assets/front/wolive_" . $login['business_id'] . ".js");


        $group = Admins::table('wolive_group')->where('business_id', $login['business_id'])->select();

        $html = '';
        foreach ($group as $v) {

            $html .= '<p class="wolive-item" onclick="wolive.blank(' . $v['id'] . ')">' . $v['groupname'] . '</p>';
        }

        try {

            $file = file_put_contents(ROOT_PATH . "/public/assets/front/wolive_" . $login['business_id'] . ".js", "
             
             /**
              *
              * wolive 标准窗口,js代码
              * 
              */
             
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
                link.type='text/css';
                link.rel = 'stylesheet';
                link.href ='{$url}/assets/css/index/wolive_online.css';
                head.appendChild(link);

            var wolive ={
                 visiter_id:'',
                 visiter_name:'',
                 avatar:'',
                 product:'',
                 open:function(){
                    var d =document.getElementById('wolive-box');
                    if(!d){
                      var div =document.createElement('div');
                      div.id ='wolive-kefu';
                      div.className +='wolive-form';
                      document.body.appendChild(div);
                      var w =document.getElementById('wolive-kefu');
                      w.innerHTML=' <i class=\"wolive-icon\"></i><p class=\"wolive-item\" onclick=\"wolive.blank(0)\" >在线咨询</p>" . $html . "';
                    }

                 },
                 blank:function(groupid){

                

                  var web ='{$url}/index/index/home?visiter_id='+encodeURIComponent(this.visiter_id)+'&visiter_name='+encodeURIComponent(this.visiter_name)+'&avatar='+encodeURIComponent(this.avatar)+'&business_id={$business_id}&groupid='+groupid+'&product='+encodeURIComponent(this.product);
                      
                  var moblieweb = '{$url}/mobile/index/home?visiter_id='+encodeURIComponent(this.visiter_id)+'&visiter_name='+encodeURIComponent(this.visiter_name)+'&avatar='+encodeURIComponent(this.avatar)+'&business_id={$business_id}&groupid='+groupid+'&product='+encodeURIComponent(this.product);

                   if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
                     window.open(moblieweb); 
                   }else{
                     window.open(web); 
                   }
                 },
            }

            window.onload =wolive.open();
        ");

            if ($file) {
                if ($js) {
                    $path = $url . "/assets/front/wolive_" . $login['business_id'] . ".js?v=" . time();
                    $data = ['code' => 0, 'msg' => '新生成js成功!', 'data' => $path];
                    return $data;
                } else {
                    $path = $url . "/assets/front/wolive_" . $login['business_id'] . ".js";
                    $data = ['code' => 0, 'msg' => '生成js成功!', 'data' => $path];
                    return $data;
                }
            }
        } catch (\Exception $e) {

            $error = $e->getMessage();
            $data = ['code' => 1, 'msg' => $error, 'data' => ''];
            return $data;
        }
    }

    /**
     *
     * [createMinjs description]
     * @return [type] [description]
     */
    public function createMinjs()
    {

        $http_type = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';


        $login = $_SESSION['Msg'];
        $business_id = $login['business_id'];
        $url = $http_type . $_SERVER['HTTP_HOST'];

        $js = @file_get_contents($url . "/assets/layer/wolive_" . $login['business_id'] . ".js");

        $group = Admins::table('wolive_group')->where('business_id', $login['business_id'])->select();

        $html = '';
        foreach ($group as $v) {
            $html .= '<p class="wolive-item" onclick="wolive.connenct(' . $v['id'] . ')">' . $v['groupname'] . '</p>';
        }

        try {

            $file = file_put_contents(ROOT_PATH . "/public/assets/layer/wolive_" . $login['business_id'] . ".js", "
            /**
             *
             * wolive 浮层版 客服咨询js
             * [wolive description]
             * @return {[type]} [description]
             */

                var head = document.getElementsByTagName('head')[0];
                var link = document.createElement('link');
                    link.type='text/css';
                    link.rel = 'stylesheet';
                    link.href ='{$url}/assets/css/index/wolive_online.css';
                    head.appendChild(link);

                var wolive ={
                     visiter_id:'',
                     visiter_name:'',
                     avatar:'',
                     product:'',
                     open:function(){
                        var d =document.getElementById('wolive-box');
                        if(!d){
                            var div =document.createElement('div');
                            div.id =\"wolive-kefu\";
                            div.className +='wolive-form';
                            document.body.appendChild(div);
                            var w =document.getElementById('wolive-kefu');
                            w.innerHTML=' <i class=\"wolive-icon\"></i><p class=\"wolive-item\" onclick=\"wolive.connenct(0)\" >在线咨询</p>" . $html . "';
                        }
                     },
                     connenct:function(groupid){
                      var id =groupid;
                      var web =encodeURI('{$url}/layer?visiter_id='+this.visiter_id+'&visiter_name='+this.visiter_name+'&avatar='+this.avatar+'&business_id={$business_id}&groupid='+groupid+'&product='+this.product);
                      
                      var moblieweb = encodeURI('{$url}/mobile/index/home?visiter_id='+this.visiter_id+'&visiter_name='+this.visiter_name+'&avatar='+this.avatar+'&business_id={$business_id}&groupid='+groupid+'&product='+this.product);

                       if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
                        
                         window.open(moblieweb); 
                       
                       }else{

                       var s =document.getElementById('wolive-talk');
                        
                       if(!s){

                            var div = document.createElement('div');
                            div.id =\"wolive-talk\";
                            div.name=id;
                            document.body.appendChild(div);
                            div.innerHTML='<i class=\"wolive-close\" onclick=\"wolive.narrow()\"></i><iframe id=\"wolive-iframe\" src=\"'+web+'\"></iframe>'
                          
                        }else{
                           
                            var title =s.name;
                            if(title == groupid){
                                s.style ='display:block';
                            }else{
                                s.parentNode.removeChild(s);
                                wolive.connenct(groupid); 
                            }
                        }
                      }
                     },
                     narrow:function(){
                        document.getElementById('wolive-talk').style=\"display:none\";
                     }
                }

                window.onload =wolive.open();

        ");

            if ($file) {
                if ($js) {
                    $path = $url . "/assets/layer/wolive_" . $login['business_id'] . ".js?v=" . time();
                    $data = ['code' => 0, 'msg' => '新生成js成功!', 'data' => $path];
                    return $data;
                } else {
                    $path = $url . "/assets/layer/wolive_" . $login['business_id'] . ".js";
                    $data = ['code' => 0, 'msg' => '生成js成功!', 'data' => $path];
                    return $data;
                }
            }

        } catch (\Exception $e) {
            $error = $e->getMessage();
            $data = ['code' => 1, 'msg' => $error, 'data' => ''];
            return $data;
        }

    }

    protected function formatTime($time)
    {
        $rtime = date("m-d H:i", $time);
        $htime = date("H:i", $time);
        $time = time() - $time;
        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor($time / 60);
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor($time / (60 * 60));
            $str = $h . '小时前 ';
        } elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor($time / (60 * 60 * 24));
            if ($d == 1) {
                $str = '昨天 ' . $rtime;
            } else {
                $str = '前天 ' . $rtime;
            }
        } else {
            $str = $rtime;
        }
        return $str;
    }

}
